package com.dz.scrm.mvp.ui;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.dz.scrm.push.JPushHelper;
import com.dz.scrm.BuildConfig;
import com.dz.scrm.R;
import com.dz.scrm.mvp.model.entity.CompanyInfoBean;
import com.dz.scrm.mvp.model.entity.LoginBean;
import com.dz.scrm.mvp.model.entity.MsgCodeBean;
import com.dz.scrm.mvp.presenter.UserPresenter;
import com.dz.scrm.utils.AppUtils;
import com.dz.scrm.utils.CheckUtils;
import com.dz.scrm.utils.HelperKt;
import com.dz.scrm.utils.LoggerUtils;
import com.dz.scrm.utils.SharedPreferencesUtil;
import com.dz.scrm.utils.TimerUtils;
import com.dz.scrm.utils.ToastUtils;
import com.google.gson.Gson;
import com.miui.enterprise.sdk.ApplicationManager;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.io.Serializable;

import butterknife.BindView;
import butterknife.OnClick;
import me.jessyan.art.integration.AppManager;
import me.jessyan.art.mvp.IView;
import me.jessyan.art.mvp.Message;
import me.jessyan.art.utils.ArtUtils;

import static com.dz.scrm.app.config.MessageWhatTagsKt.*;
import static com.dz.scrm.utils.SharedPreferencesUtil.RegistrationID;


/**
 * @Description: 登录页面
 * @Author: 黄海
 * @CreateDate: 2021-4-22 9:42
 * @UpdateUser: 黄海
 * @UpdateDate: 2021-4-22 9:42
 * @UpdateRemark: 更新说明
 */
public class LoginActivity extends DZActivity<UserPresenter> implements IView {
    @BindView(R.id.edTel)
    EditText edTel;
    @BindView(R.id.imgClose)
    ImageView imgClose;
    @BindView(R.id.tvNext)
    TextView tvNext;
    @BindView(R.id.msgLayout)
    ConstraintLayout msgLayout;
    @BindView(R.id.tvSendPhone)
    TextView tvSendPhone;
    @BindView(R.id.edMsg)
    EditText edMsg;
    @BindView(R.id.tvSendTime)
    TextView tvSendTime;
    @BindView(R.id.tvMsgNext)
    TextView tvMsgNext;
    //倒计时时间
    private int timeAll = 60;

    @Override
    public int initView(@Nullable Bundle savedInstanceState) {
        return R.layout.activity_login;
    }

    @Override
    public void initData(@Nullable Bundle savedInstanceState) {
        initSDKPermission();
        if (HelperKt.isAlreadyLogin()) {
            // 直接跳转到首页，无需再次登录
            ArtUtils.startActivity(HomeActivity.class);
            finish();
        }
        tvNext.setEnabled(false);
        tvNext.setAlpha(0.4f);
        msgLayout.setVisibility(View.GONE);
        edTel.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                int isFormatRightPhone = CheckUtils.checkRightPhone(s.toString());
                switch (isFormatRightPhone) {
                    case 0:
                        tvNext.setEnabled(false);
                        imgClose.setVisibility(View.VISIBLE);
                        tvNext.setAlpha(0.4f);
                        break;

                    case 1:
                        ToastUtils.showToastMsg(LoginActivity.this, "请输入正确的手机号码");
                        tvNext.setEnabled(false);
                        imgClose.setVisibility(View.VISIBLE);
                        tvNext.setAlpha(0.4f);
                        break;

                    case 2:
                        tvNext.setEnabled(true);
                        imgClose.setVisibility(View.VISIBLE);
                        tvNext.setAlpha(1f);
                        break;

                    case 3:
                        tvNext.setEnabled(false);
                        imgClose.setVisibility(View.INVISIBLE);
                        tvNext.setAlpha(0.4f);
                        break;
                }
            }
        });

        edMsg.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                                          int after) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (!TextUtils.isEmpty(s.toString())) {
                    if (s.toString().length() == 4) {
                        //表示验证码输入完毕，高亮显示下一步
                        tvMsgNext.setEnabled(true);
                        tvMsgNext.setAlpha(1f);
                    } else {
                        tvMsgNext.setEnabled(false);
                        tvMsgNext.setAlpha(0.4f);
                    }
                } else {
                    tvMsgNext.setEnabled(false);
                    tvMsgNext.setAlpha(0.4f);
                }
            }
        });
    }


    /***isHidenPhoneNum
     * 给APP添加权限
     */
    private void initSDKPermission() {
        ApplicationManager.getInstance().setApplicationSettings(AppUtils.getPackageName(this),
                ApplicationManager.FLAG_KEEP_ALIVE |
                        ApplicationManager.FLAG_GRANT_ALL_RUNTIME_PERMISSION |
                        ApplicationManager.FLAG_ALLOW_AUTOSTART
                        /*|ApplicationManager.FLAG_PREVENT_UNINSTALLATION, 0*/);

    }

    @Nullable
    @Override
    public UserPresenter obtainPresenter() {
        // P层注入
        return new UserPresenter(ArtUtils.obtainAppComponentFromContext(this), new RxPermissions(this));
    }

    @Override
    public void showMessage(@NonNull String message) {
        ToastUtils.showToastMsg(LoginActivity.this, message);
    }

    @Override
    public void handleMessage(@NonNull Message message) {
        switch (message.what) {
            case WHAT_LOGIN_SUCCESS:
                //登录成功
                LoginBean loginBean = (LoginBean) message.obj;
                if (message != null && message.obj != null) {
                    if (loginBean != null && loginBean.getList() != null) {
                        loginBean.setPhoneNum(edTel.getText().toString());
                        Intent intent = new Intent();
                        SharedPreferencesUtil.saveInfo(SharedPreferencesUtil.PHONE_NUM, edTel.getText().toString());
                        SharedPreferencesUtil.saveInfo(SharedPreferencesUtil.LOGIN_INFO, new Gson().toJson(loginBean));
                        TimerUtils.getInstance().cancel(TAG);
                        if (loginBean.getList() != null) {
                            if (loginBean.getList().size() > 1) {
                                //切列表大于1 的时候直接跳过企业选择
                                intent.setClass(this, ChooseCompany.class);
                                intent.putExtra("phoneNum", edTel.getText().toString());
                                intent.putExtra("verify", loginBean.getVerify());
                                intent.putExtra("data", (Serializable) loginBean.getList());
                                startActivity(intent);
                                finish();
                            } else if (loginBean.getList().size() == 1) {
                                //直接跳转到首页,先获取到企业信息保存
                                Message msg = Message.obtain(this);
                                if (loginBean.getList().get(0) != null) {
                                    LoggerUtils.d("checkCompany：" + SharedPreferencesUtil.getInfo(RegistrationID));
                                    mPresenter.checkCompany(msg, loginBean.getPhoneNum(), loginBean.getList().get(0).getTenantId(),
                                            loginBean.getVerify(), JPushHelper.INSTANCE.getRegistrationID(this));
                                } else {
                                    //获取企业信息失败

                                }
                            }
                        }
                    }
                }

                break;

            case WHAT_LOGIN_GAECODE_SUCCESS:
                //获取验证码成功
                if (message != null && message.obj != null) {
                    MsgCodeBean msgCodeBean = (MsgCodeBean) message.obj;
                    if (msgCodeBean != null) {
                        String toastMsg = "";
                        if (msgCodeBean.getError_code() == 200) {
                            //表示验证码获取成功
                            toastMsg = "验证码已发送";
                            msgLayout.setVisibility(View.VISIBLE);
                            tvMsgNext.setEnabled(false);
                            tvMsgNext.setAlpha(0.4f);
                            ShowCode();
                        } else if (msgCodeBean.getError_code() == 400) {
                            //验证码获取失败
                            toastMsg = msgCodeBean.getError_description() + "";
                        }
                        ToastUtils.showToastMsg(LoginActivity.this, toastMsg);
                    }
                }
                break;

            case WHAT_CHECK_COMPANY_SUCCESS:
                //企业验证成功
                CompanyInfoBean companyInfoBean = (CompanyInfoBean) message.obj;
                if (message != null && message.obj != null) {
                    //保存企业信息
                    if (companyInfoBean != null) {
                        SharedPreferencesUtil.saveInfo(SharedPreferencesUtil.COMPANY_INFO, new Gson().toJson(companyInfoBean));
                        SharedPreferencesUtil.saveInfo(SharedPreferencesUtil.TOKEN, companyInfoBean.getAccess_token());
                        isHidenPhoneNum(companyInfoBean.is_hidden());
                        Intent intent = new Intent();
                        intent.setClass(this, HomeActivity.class);
                        startActivity(intent);
                        AppManager.getAppManager().killAll();
                    }
                }
        }
    }

    @OnClick({R.id.imgClose, R.id.tvNext, R.id.tvMsgNext, R.id.tvSendTime})
    public void onViewClicked(View view) {
        if (view == imgClose) {
            //清空ed
            edTel.setText("");
        } else if (view == tvNext) {
            //下一步获取验证码
            Message msg = Message.obtain(this, edTel.getText().toString());
            mPresenter.getCode(msg);
        } else if (view == tvMsgNext) {

            //下一步登录
            Message msg = Message.obtain(this);
            mPresenter.Login(msg, edTel.getText().toString(), edMsg.getText().toString());
        } else if (view == tvSendTime) {
            //倒计时
            Message msg = Message.obtain(this, edTel.getText().toString());
            mPresenter.getCode(msg);
        }
    }

    /***
     * 获取短信验证码成功
     */
    private void ShowCode() {
        tvSendPhone.setText("验证码已发送至 +86 " + edTel.getText());
        timeShow();
    }

    /*倒计时*/

    private void timeShow() {
        timeAll = 60;
        isCanGetCode(false);
        TimerUtils.getInstance().cancel(TAG);
        TimerUtils.getInstance().interval(TAG, 1000, new TimerUtils.TimerDoNext() {
            @Override
            public void doNext() {
                timeAll--;
                if (timeAll <= 0) {
                    TimerUtils.getInstance().cancel(TAG);
                    isCanGetCode(true);
                } else {
                    tvSendTime.setText(timeAll + "s后重新获取");
                    edMsg.requestFocus();
                }
            }
        });
    }

    private void isCanGetCode(boolean hideOrShow) {
        if (hideOrShow) {
            tvSendTime.setText("获取验证码");
            tvSendTime.setClickable(true);
            tvSendTime.setEnabled(true);
        } else {
            tvSendTime.setText(timeAll + "s后重新获取");
            tvSendTime.setEnabled(false);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        TimerUtils.getInstance().cancel(TAG);
        ToastUtils.reset();
    }
}
